package com.example.guiguiapplicatio.fragment.followup;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Entity.FollowUp;

import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.LocalSaveActivity;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.Record;
import com.example.guiguiapplicatio.databinding.FragmentNewChildBinding;
import com.example.guiguiapplicatio.databindingBean.Followupnewchild;
import com.example.guiguiapplicatio.databindingBean.followup.FollowupWith;
import com.example.guiguiapplicatio.databindingBean.followup.ListFollowupWith;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.example.guiguiapplicatio.utils.EditIsCanUseBtnUtils;
import com.example.guiguiapplicatio.utils.JsonUtil;
import com.example.guiguiapplicatio.utils.PreferencesUtil;
import com.example.guiguiapplicatio.utils.ToastUtil;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;

import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class NewChildFragment extends Fragment {

    private FragmentNewChildBinding binding;

    private RadioButton tempButton;

    private Retrofit retrofit;
    private Api api;
    private Record record;
    private FollowUp followUp;
    private Followupnewchild tempNewChild = null;//预保存随访数据对象以作比较
    private int doctorId;
    private FollowupWith followupWith;
    private ListFollowupWith listFollowupWith;
    private Followupnewchild newChildBean = null;//当前数据对象
    private boolean IS_FOLLOWUP_TO_REPORT_THIS = false;
    private boolean IS_EXIST_FOLLOWUP_TO_THIS = false;
    private boolean IS_WITHOUT_NET = false;
    NavController navController;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        // retrofit2初始化
        OkHttpClient client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .baseUrl(getString(R.string.api))
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
        // retrofit2初始化

        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentNewChildBinding.inflate(inflater, container, false);
        navController = Navigation.findNavController(container);
        initDate();


        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (getActivity() != null) {
                    tempButton = getActivity().findViewById(checkedId);
                    newChildBean.setSex((String) tempButton.getText());
                }

            }
        });

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });


        inClick();

        setSelectWay(binding.selectWayBtn, binding.selectWayLayout, IS_EXIST_FOLLOWUP_TO_THIS);

        return binding.getRoot();
    }

    private void setEditWall() {
        binding.editWall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getContext() != null) {
                    ToastUtil.showToast(getContext(), "非该随访医师不可编辑！");

                }
            }
        });

        if (!followUp.getDoctorId().equals(doctorId)) {
            binding.editWall.setVisibility(View.VISIBLE);
        }
    }

    private void setLocalSave() {
        ActivityResultLauncher launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if (result.getResultCode() == Activity.RESULT_OK) {

                    Log.d("data_return", result.getData().getStringExtra("data_return"));
                    Gson gson = new Gson();
                    String dataReturn = result.getData().getStringExtra("data_return");

                    String json = dataReturn.substring(1, dataReturn.length() - 1).replaceAll("\\\\", "");


                    newChildBean = gson.fromJson(json, Followupnewchild.class);
                    configurationData(true);

                }
            }
        });

        Intent intent = new Intent(getActivity(), LocalSaveActivity.class);
        binding.saveLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Gson gson = new Gson();
                intent.putExtra("dataType", newChildBean.getClass().getName());
                intent.putExtra("data", gson.toJson(newChildBean));
                intent.putExtra("IS_SAVE", true);
                launcher.launch(intent);//启动intent跳转
            }
        });

        binding.loadLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                intent.putExtra("dataType", newChildBean.getClass().getName());
                intent.putExtra("IS_SAVE", false);
                launcher.launch(intent);//启动intent跳转
            }
        });

    }

    private void configurationData(boolean isReload) {

        //拷贝
        Gson gson = new Gson();
        tempNewChild = gson.fromJson(gson.toJson(newChildBean), Followupnewchild.class);
        //拷贝
        Log.e("gson.toJson(newChildBean),", "//拷贝 gson.toJson(newChildBean),: " + gson.toJson(newChildBean));


        if (!(newChildBean.getSex() == null)) {
            switch (newChildBean.getSex()) {
                case "男":
                    binding.sexNan.setChecked(true);
                    break;
                case "女":
                    binding.sexNv.setChecked(true);
                    break;
                case "未说明性别":
                    binding.sexWeishuoming.setChecked(true);
                    break;
                case "未知性别":
                    binding.sexWeizhi.setChecked(true);
                    break;
                default:
                    break;
            }
        }

        if (!isReload) {
            binding.name.setText(listFollowupWith.getPatientName());
            setEditWall();
        }

        followupWith = new FollowupWith();
        followupWith.setFollow(followUp);
        followupWith.setObject(newChildBean);
        binding.setChild(newChildBean);


    }

    private void initDate() {

        if (getArguments().getBoolean("IS_EXIST_FOLLOWUP_TO_THIS")) {
            IS_EXIST_FOLLOWUP_TO_THIS = getArguments().getBoolean("IS_EXIST_FOLLOWUP_TO_THIS");
        }

        if (getArguments().getBoolean("IS_FOLLOWUP_TO_REPORT_THIS")) {
            IS_FOLLOWUP_TO_REPORT_THIS = getArguments().getBoolean("IS_FOLLOWUP_TO_REPORT_THIS");
        }

        IS_WITHOUT_NET = getArguments().getBoolean("IS_WITHOUT_NET");

        doctorId = PreferencesUtil.getInt(getContext(), "doctor_id");

        if (IS_EXIST_FOLLOWUP_TO_THIS) {
            listFollowupWith = (ListFollowupWith) getArguments().getSerializable("ListFollowupWith");
            followUp = listFollowupWith.getFollowUp();

            Call<ResponseBody<FollowupWith>> call = api.getOneFollowupWith(followUp.getId());
            call.clone().enqueue(new Callback<ResponseBody<FollowupWith>>() {
                @Override
                public void onResponse(Call<ResponseBody<FollowupWith>> call, Response<ResponseBody<FollowupWith>> response) {
                    ResponseBody<FollowupWith> responseBody = response.body();
                    if (!responseBody.equals(null)) {
                        if (responseBody.getMsg().equals("无数据")) {
                            Toast.makeText(getContext(), "错误!无数据", Toast.LENGTH_LONG).show();
                            getActivity().onBackPressed();
                        } else {
                            String json = JsonUtil.toJson(responseBody.getData().getObject());
                            newChildBean = JsonUtil.fromJson(json, Followupnewchild.class);

                            configurationData(false);

                        }

                    } else {
                        Toast.makeText(getContext(), "数据获取错误", Toast.LENGTH_LONG).show();
                        getActivity().onBackPressed();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody<FollowupWith>> call, Throwable t) {
                    if (getContext() != null) {
                        Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                        getActivity().onBackPressed();
                    }
                }
            });

        } else {
            followupWith = new FollowupWith();
            followUp = new FollowUp();
            newChildBean = new Followupnewchild();
            binding.setChild(newChildBean);

            record = (Record) getArguments().getSerializable("Record");
            followUp.setFollowUpType("新生儿");
            followUp.setIdCard(record.getIdcard());
            followUp.setDoctorId(doctorId);

            newChildBean.setIdNum(record.getIdcard());
            binding.name.setText(record.getName());
            followupWith.setFollow(followUp);
            followupWith.setObject(newChildBean);


        }


    }

    private void setSelectWay(Button selectWayBtn, LinearLayout selectWayLayout, boolean IS_EXIST) {
        selectWayLayout.setVisibility(View.GONE);
        selectWayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectWayLayout.getVisibility() == View.VISIBLE) {
                    selectWayLayout.setVisibility(View.GONE);
                } else {
                    selectWayLayout.setVisibility(View.VISIBLE);
                }
            }
        });

        if (IS_EXIST) {
            if (followUp.getState() == 0) {//草稿
                binding.saveLocal.setVisibility(View.GONE);
                binding.save.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
            } else if (followUp.getState() == 1) { //正式
                binding.updataToFormal.setVisibility(View.GONE);
                binding.save.setVisibility(View.GONE);
                binding.delete.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
                binding.saveLocal.setVisibility(View.GONE);
                binding.loadLocal.setVisibility(View.GONE);
            }

        } else {//新增

            binding.updataToFormal.setVisibility(View.GONE);
            binding.updata.setVisibility(View.GONE);
            binding.delete.setVisibility(View.GONE);
            if (IS_WITHOUT_NET) {//无网络
                binding.save.setVisibility(View.GONE);
                binding.upload.setVisibility(View.GONE);
            }
        }


    }

    private void inClick() {

        binding.updata.setOnClickListener(new View.OnClickListener() {//更新
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                if (newChildBean.equals(tempNewChild)) {
                    Toast.makeText(getContext(), "无更新", Toast.LENGTH_LONG).show();          //注意
                } else {

                    Call<ResponseBody<Object>> objectCall = api.updateFollowUp(followupWith);
                    dialogToApi("确认更新？", objectCall);
                }
            }
        });


        binding.upload.setOnClickListener(new View.OnClickListener() {//上传网络
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);

                Boolean haveEmpty = EditIsCanUseBtnUtils.getInstance().addEdittext(binding.adress)
                        .addEdittext(binding.fatherName)
                        .addEdittext(binding.motherName)
                        .addEdittext(binding.fatherPhoneNum)
                        .addEdittext(binding.motherPhoneNum)
                        .build();

                if (haveEmpty == true) {//检测限制的的输入框是有空

                    Toast.makeText(getContext(), "请继续完善信息", Toast.LENGTH_LONG).show();

                } else {
                    followUp.setState(1);
                    Call<ResponseBody<Object>> objectCall = api.upLoadFollowUp(followupWith);
                    dialogToApi("确认上传正式随访？", objectCall);

                }

            }
        });

        binding.save.setOnClickListener(new View.OnClickListener() {//保存网络
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                followUp.setState(0);
                Call<ResponseBody<Object>> objectCall = api.upLoadFollowUp(followupWith);
                dialogToApi("确认上传随访草稿？", objectCall);
            }
        });

        binding.updataToFormal.setOnClickListener(new View.OnClickListener() {//转为正式
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Boolean haveEmpty = EditIsCanUseBtnUtils.getInstance().addEdittext(binding.adress)
                        .addEdittext(binding.fatherName)
                        .addEdittext(binding.motherName)
                        .addEdittext(binding.fatherPhoneNum)
                        .addEdittext(binding.motherPhoneNum)
                        .build();

                if (haveEmpty == true) {//检测限制的的输入框是有空

                    Toast.makeText(getContext(), "请继续完善信息", Toast.LENGTH_LONG).show();

                } else {
                    followUp.setState(1);
                    Call<ResponseBody<Object>> objectCall = api.updateFollowUp(followupWith);
                    dialogToApi("确认转为正式随访？", objectCall);

                }
            }

        });

        binding.delete.setOnClickListener(new View.OnClickListener() {//删除草稿
            @Override
            public void onClick(View v) {
                binding.selectWayLayout.setVisibility(View.GONE);
                Call<ResponseBody<Object>> objectCall = api.deleteFollowUp(followupWith);
                dialogToApi("确认删除随访草稿？", objectCall);
            }
        });


        setLocalSave();

    }

    private void dialogToApi(String title, Call<ResponseBody<Object>> objectCall) {
        AlertDialog aldg;
        AlertDialog.Builder adBd = new AlertDialog.Builder(getContext());
        adBd.setTitle(title);
        adBd.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.e("objectCall", " objectCall: " + objectCall);
                objectCall.clone().enqueue(new Callback<ResponseBody<Object>>() {

                    @Override
                    public void onResponse(Call<ResponseBody<Object>> call, Response<ResponseBody<Object>> response) {
                        if (response.body() != null) {
                            Toast.makeText(getContext(), response.body().getMsg(), Toast.LENGTH_SHORT).show();
                            if (IS_FOLLOWUP_TO_REPORT_THIS) {
                                getActivity().onBackPressed();
                            } else {
                                navController.navigate(R.id.action_newChildFragment_to_navigation_follow_up);
                            }
                            ///代码复用注意修改
                        } else {
                            Log.e("onResponse", "onResponse:   为空！！");
                            if (getContext() != null) {
                                Toast.makeText(getContext(), "onResponse:   为空！！", Toast.LENGTH_LONG).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<Object>> call, Throwable t) {
                        Log.e("onFailure", "onFailure: ！" + t);
                        if (getContext() != null) {
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
        adBd.setNegativeButton("取消", null);
        aldg = adBd.create();
        aldg.show();

    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }


}
